<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>简单计算器</title>
    <script type="text/javascript">
        // 获取输入值并验证是否为数字
        function getInputValue(id) {
            const value = parseFloat(document.getElementById(id).value);  //const 让值不可更改， parseFloat(document.getElementById(id).value)获取文本框内容，并将其转换为浮点数
            if (isNaN(value)) {
                document.getElementById("third").value = "只能输入数字";
                return null;
            }
            return value;
        }

        // 设置计算结果
        function setResult(result) {
            document.getElementById("third").value = result.toFixed(15) - 0; // 精确到小数点第15位，去掉多余的0
        }

        // 通用计算方法
        function calculate(operator) {
            const number1 = getInputValue("first");
            const number2 = getInputValue("second");
            if (number1 === null || number2 === null) return;

            let result;
            switch (operator) {
                case '+':
                    result = number1 + number2;
                    break;
                case '-':
                    result = number1 - number2;
                    break;
                case '*':
                    result = number1 * number2;
                    break;
                case '/':
                    if (number2 === 0) {
                        document.getElementById("third").value = "除数不能为0";
                        return;
                    }
                    result = number1 / number2;
                    break;
                default:
                    document.getElementById("third").value = "无效操作符";
                    return;
            }

            setResult(result);
        }
    </script>
</head>
<body>
    第一个数：<input type="text" id="first" /><br>
    第二个数：<input type="text" id="second" /><br>
    <button onclick="calculate('+')">+</button>
    <button onclick="calculate('-')">-</button>
    <button onclick="calculate('*')">*</button>
    <button onclick="calculate('/')">/</button><br>
    计算结果：<input type="text" id="third" readonly /><br>
</body>
</html>